package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.annotation.WebFilter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrdersServiceImpl implements OrdersService {
    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);
    }



    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        // 检查参数(健壮性判断) 地址id是否有数据
        Long addressBookId = ordersSubmitDTO.getAddressBookId();
        if (addressBookId == null) {
            // 地址为空则抛出自定义异常
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        // 准备数据
        // 根据用户id查询购物车信息
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getByUserId(BaseContext.getCurrentId());
        // 判断购物车是否有数据
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            // 购物车没有数据抛出自定义异常
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        // 获取地址信息
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        // 检查用户的收获地址是否超出配送范围
        checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        // 封装订单数据, 到orders订单表
        Orders orders = new Orders();
        // 补充订单号
        orders.setNumber(String.valueOf(System.currentTimeMillis())); // 获取系统时间做订单号(或UUID)
        // 状态
        orders.setStatus(Orders.PENDING_PAYMENT); // 待付款
        // 操作用户id
        orders.setUserId(BaseContext.getCurrentId());
        // 将前端提交的数据拷贝到orders订单表
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 设置收获地址相关信息
        orders.setAddress(
                addressBook.getProvinceName() +
                        addressBook.getCityName() +
                        addressBook.getDistrictName() +
                        addressBook.getDetail());
        // 电话
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        // 下单时间
        orders.setOrderTime(LocalDateTime.now());
        // 支付状态
        orders.setPayStatus(0);
        ordersMapper.insert(orders);

        // 封装订单明细数据 ,到order_detail
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            //
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            // 设置订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        // 向订单明细表增加数据
        orderDetailMapper.insertBatch(orderDetailList);
        // 清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        // 来单提醒
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "王大帅气的订单号");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        // 封装结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setOrderTime(orders.getOrderTime());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        return orderSubmitVO;
    }

    /**
     * 历史订单查询
     *
     * @param
     * @return
     */
    @Override
    public PageResult history(int page, int pageSize, Integer status) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);
        // 设置当前操作人ID
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        // 设置条件查询
        Page<Orders> pg = ordersMapper.history(ordersPageQueryDTO);
        // 查出订单明细 封装到VO
        List<OrderVO> list = new ArrayList();
        if (pg != null && pg.getTotal() > 0) {
            //
            for (Orders orders : pg) {
                // 取出ID
                Long orderId = orders.getId();
                // 根据id获取订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);
                // 将订单明细封装到VO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        return new PageResult(pg.getTotal(), list);
    }

    /**
     * 查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO orderDetail(Long id) {
        // 根据id查询订单
        Orders orders = ordersMapper.getById(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());
        // 封装到VO
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    @Override
    public void cancel(Long id) {
        // 根据id将订单查出来
        Orders orders = ordersMapper.getById(id);
        // 判断订单是否存在
        if (orders == null) {
            // 提示 订单不存在
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 判断订单状态
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 符合取消的条件 设置Orders的id,状态,取消原因,取消时间
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消");
        orders1.setCancelTime(LocalDateTime.now());
        // 调用ordersMapper方法更新订单信息
        ordersMapper.update(orders1);
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
        // 根据id获取订单信息
        Orders byId = ordersMapper.getById(id);
        // 在根据订单信息获取订单详情数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(byId.getId());
        // 创建ShoppingCart对象
        ShoppingCart shoppingCart = new ShoppingCart();
        // 创建一个泛型为ShoppingCart的List类型的集合,用于封装购物车信息
        List<ShoppingCart> shoppingCartList = new ArrayList<>();
        // 遍历订单详情数据, 因为一个订单中可能有多个菜品的信息,要将每个菜品信息给购物车集合
        for (OrderDetail orderDetail : orderDetailList) {
            // 将拿到的每一个详情信息拷贝到购物车对象
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            // 补充信息
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 将购物车对象添加到购物车集合中
            shoppingCartList.add(shoppingCart);
        }
        // 调用购物车添加方法
        shoppingCartMapper.insertBatch(shoppingCartList);

    }


    //////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 条件查询: 订单号,手机号模糊查询 对下单时间筛选
        Page<OrderVO> orders = ordersMapper.list(ordersPageQueryDTO);
        for (OrderVO order : orders) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(order.getId());
            StringBuilder builder = new StringBuilder();
            for (OrderDetail orderDetail : orderDetailList) {
                builder.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(";");
            }
            order.setOrderDishes(builder.toString());
            order.setOrderDetailList(orderDetailList);
        }
        return new PageResult(orders.getTotal(),orders.getResult());
    }
    /*@Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页参数
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        // 条件查询: 订单号,手机号模糊查询 对下单时间筛选
        Page<Orders> ordersPage = ordersMapper.page(ordersPageQueryDTO);
        // 待结单,待派送,已派送 需要显示菜品信息
        // 将orders转换为VO对象
        List<OrderVO> orderVOList = getOrderVO(ordersPage);
        // 最后封装为表现层需要的格式
        PageResult pageResult = new PageResult();
        pageResult.setTotal(ordersPage.getTotal());
        pageResult.setRecords(orderVOList);
        return pageResult;
    }*/


    // 将orders转成VO
    private List<OrderVO> getOrderVO(Page<Orders> ordersPage) {
        // 创建一个VO集合
        ArrayList<OrderVO> voArrayList = new ArrayList<>();
        // 使用ordersPage.getResult方法获取orders集合
        List<Orders> ordersList = ordersPage.getResult();
        // 判断orders集合是否为空
        if (ordersList != null) {
            // 遍历orders集合,将取出的每一个元素给VO
            for (Orders orders : ordersList) {
                // 创建一个VO对象
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                // 获取orders中的菜品信息
                String orderDish = getOrderDish(orders);
                // 将菜品信息添加到VO对象
                orderVO.setOrderDishes(orderDish);
                // 将VO对象添加到VO集合
                voArrayList.add(orderVO);
            }
        }
        // 返回 VO集合
        return voArrayList;
    }

    // 根据订单id获取菜品信息字符串
    public String getOrderDish(Orders orders) {
        // 菜品信息在订单详情里
        // 根据订单id获取订单详情
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(orders.getId());
        // 创建一个dish对象用来最后的封装
        List<String> dish = new ArrayList<>();
        // 遍历刚刚得到的订单详情集合, 取出其中的菜品名称和对应的数量,添加到dish集合
        for (OrderDetail orderDetail : byOrderId) {
            String name = orderDetail.getName();
            String number = String.valueOf(orderDetail.getNumber());
            dish.add(name);
            dish.add(number);
        }
        return String.join(",", dish);
    }

    /**
     * 统计订单状态数量
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        // 最后返回这个VO对象
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        // 获取三个状态对应的数据
        Integer toBeConfirmed = ordersMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer Confirmed = ordersMapper.statistics(Orders.CONFIRMED);
        Integer deliveryInProgress = ordersMapper.statistics(Orders.DELIVERY_IN_PROGRESS);
        // 将获取到的数据,封装到VO
        orderStatisticsVO.setConfirmed(Confirmed);
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情(回显)
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        // 分为两部分 查询订单菜品信息  查询订单详情
        // new一个VO用于最后封装数据
        OrderVO orderVO = new OrderVO();
        // 查询订单详情
        // 先根据id查询订单,在根据订单id查询订单详情
        Orders byId = ordersMapper.getById(id);
        System.out.println(byId);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(byId.getId());
        System.out.println(orderDetailList);
        // 用之前定义的方法查询菜品信息
        String details = getOrderDish(byId);
        System.out.println(details);
        // 将查询的信息封装到VO
        orderVO.setOrderDishes(String.valueOf(byId));
        orderVO.setOrderDetailList(orderDetailList);
        System.out.println(orderVO);
        return orderVO;
    }

    /**
     * 更改订单状态(已接单)
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CONFIRMED);
        orders.setId(ordersConfirmDTO.getId());
        ordersMapper.update(orders);
    }

    /**
     * 拒单
     *
     * @param
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders = new Orders();
        Orders ordersMapperById = ordersMapper.getById(ordersRejectionDTO.getId());
        // 判断状态当前订单状态,只有当状态为待接单时才可以取消
        if (Orders.TO_BE_CONFIRMED != ordersMapperById.getStatus()) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setId(ordersRejectionDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 管理端取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        Orders orders = ordersMapper.getById(id);
        if (orders.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        ordersMapper.update(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        Orders orders = ordersMapper.getById(id);
        if(orders.getStatus() != Orders.DELIVERY_IN_PROGRESS){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        orders.setStatus(Orders.COMPLETED);
        ordersMapper.update(orders);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 每分钟检查一次待支付订单是否超时
     */
    public void checkPayTimeOut(){
        // 查询订单状态是否是待支付, 并且查询已经超时了的订单id
        // 获取十五分钟之前的时间对象
        LocalDateTime dateTime = LocalDateTime.now().plusMinutes(-15);
        // 根据两个条件查询订单id 订单状态 时间在十五分钟之前
        List<Long> ids = ordersMapper.getIdsByStatusAndTime(Orders.PENDING_PAYMENT,dateTime);
        // 修改超时订单状态为已取消
        if (ids != null && ids.size() > 0){
            for (Long id : ids) {
                ordersMapper.update(Orders.builder().status(Orders.CANCELLED).id(id).build());
            }
        }
        // 根据id修改状态
    }

    /**
     * 每天凌晨一点检查前一天是否还有派送中的订单
     */
    @Override
    public void checkProgressOrder() {
        LocalDateTime dateTime = LocalDateTime.now().plusHours(-1);
        // 根据两个条件查询订单id 订单状态 时间在十五分钟之前
        List<Long> ids = ordersMapper.getIdsByStatusAndTime(Orders.DELIVERY_IN_PROGRESS,dateTime);
        // 修改超时订单状态为已取消
        if (ids != null && ids.size() > 0){
            for (Long id : ids) {
                ordersMapper.update(Orders.builder().status(Orders.COMPLETED).id(id).build());
            }
        }
    }

    @Override
    public void reminder(Long id) {
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "王大帅气的订单号");
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
